package com.cykj.pos.controller.api;

import com.alibaba.fastjson.JSONObject;
import com.cykj.common.core.domain.AjaxResult;
import com.cykj.common.utils.SecurityUtils;
import com.cykj.pos.controller.TestDTO.FileItem;
import com.cykj.pos.controller.TestDTO.HttpClientHandler;
import com.cykj.pos.domain.*;
import com.cykj.pos.domain.dto.*;
import com.cykj.pos.domain.posone.BizAreaCodeDTO;
import com.cykj.pos.service.*;
import com.cykj.pos.service.impl.BizMerchantReceiverServiceImpl;
import com.cykj.pos.util.PosOneUtil;
import com.google.gson.Gson;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.RequiredArgsConstructor;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.*;
import java.net.URL;
import java.text.SimpleDateFormat;
import java.util.*;

@RequiredArgsConstructor(onConstructor_ = @Autowired)
@RestController
@RequestMapping("/noauth/posv1")
@Api(tags = "商户报件")
public class PosV1OperationOfmerChant {

    private final IBizPosMachineService bizPosMachineService;

    private final IBizPosTypeService iBizPosTypeService;

    private final IBizPosBrandService iBizPosBrandService;

    private final PartnerOpenInterfaceController partnerOpenInterfaceController;

    private final IBizPosErminalRateService iBizPosErminalRateService;

    private final IBizMerchantEntryService iBizMerchantEntryService;

    private final IBizMerchantListService iBizMerchantListService;

    private final IBizMerchantInquiryService iBizMerchantInquiryService;

    private final IBizMerchantBindingTerminalService iBizMerchantBindingTerminalService;

    private final IBizMerchantTerminalListService iBizMerchantTerminalListService;

    private final IBizPosMachineStatusRecordsService recordsService;

    private final IBizMerchantEntryService bizMerchantEntryService;

    private final IBizMessageRecordsService bizMessageRecordsService;

    private final IBizMerchantService bizMerchantService;

    private final BizMerchantReceiverServiceImpl bizMerchantReceiverService;

    private final IBizFeesChargedService bizFeesChargedService;


    @PostMapping("/AddMerchantMessageType")
    @ApiOperation("费率下拉")
    public AjaxResult MerchantMessageType() {
        TypeRateDTO typeRateDTO = new TypeRateDTO();
        typeRateDTO.setPosTypelist(iBizPosTypeService.selposType());
        typeRateDTO.setPosErminalRatelist(iBizPosErminalRateService.selErminalRate());
        typeRateDTO.setPosbrandNamelist(iBizPosBrandService.selposbrandName());
        return AjaxResult.success(typeRateDTO);
    }

    @PostMapping("/code")
    public AjaxResult queryRegionalCode(@RequestBody BizAreaCodeDTO bizAreaCodeDTO) {
        AjaxResult ajaxResult = AjaxResult.success("查询省市区编码");
        List<BizAreaCodeDTO> list = iBizMerchantEntryService.queryRegionalCode(bizAreaCodeDTO);
        ajaxResult.put("data", list);
        return ajaxResult;
    }


    /**
     * 商户报件
     *
     * @param bizMerchantEntry
     * @return
     * @throws Exception
     */
    @PostMapping("/Operation")
    @ApiOperation("商户报件")
    public AjaxResult startup(@RequestBody BizMerchantEntry bizMerchantEntry) throws Exception {
        AjaxResult ajaxResult = AjaxResult.success();
        ajaxResult.put("data", false);
        ajaxResult.put("retMsge", "请更新App");
        return ajaxResult;
    /*    AjaxResult ajaxResult = AjaxResult.success("商户报件");
        String snCode = bizMerchantEntry.getSn();// 设备号
        //BizMerchantEntry bizMerchantEntry1 = iBizMerchantEntryService.getBizMerchantEntryBySn(snCode);
        BizEntrySnDTO bizMerchantEntry1 = iBizMerchantEntryService.getBizEntrySn(snCode);
        if (bizMerchantEntry1 != null) {
            ajaxResult.put("data", false);
            ajaxResult.put("retMsge", "该设备已存在商户");
            return ajaxResult;
        }
        // 先进行判读
        Long merchId = 0L;
        if (null != bizMerchantEntry.getSn()) {
            String sn = bizMerchantEntry.getSn();
            BizPosMachine bizPosMachine = bizPosMachineService.getPosMachineBySnCode(snCode);
            if (null == bizPosMachine) {
                // 没有该pos机 不允许报件
                ajaxResult.put("data", false);
                ajaxResult.put("retMsge", "该设备不存在");
                return ajaxResult;
            }
            merchId = bizPosMachine.getMerchId();
            bizMerchantEntry.setMerchId(merchId);
        }
        String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=merchantinfoDao&Methods=add";
        Map<String, String> data = new HashMap<String, String>();
        data.put("phone", bizMerchantEntry.getPhone());// 手机号
        data.put("applicant", bizMerchantEntry.getApplicant());// 姓名
        data.put("provinceno", bizMerchantEntry.getProvinceno());// 省编号
        data.put("cityno", bizMerchantEntry.getCityno());// 城市编号
        data.put("areano", bizMerchantEntry.getAreano());// 区编号
        data.put("certificateno", bizMerchantEntry.getCertificateno());// 身份证
        data.put("certificatestartdate", bizMerchantEntry.getCertificatestartdate());// 身份证开始时间
        data.put("certificateenddate", bizMerchantEntry.getCertificateenddate());// 身份证结束时间
        data.put("bankcardaccount", bizMerchantEntry.getBankcardaccount());// 银行卡号
        data.put("fee_chl_id", bizMerchantEntry.getFeeChlId());// 费率终端id
        data.put("sn", bizMerchantEntry.getSn());// 设备号
        if (bizMerchantEntry1 != null) {
            *//*String merchantNo = iBizMerchantEntryService.findMerchantNo(bizMerchantEntry.getSn()); //系统商户编号*//*
            data.put("merchant_no", bizMerchantEntry1.getMerchantNo());
        }
        data.put("mersource", "OUTMER");
        data.put("agentid", secretAgentid);
        data.put("key", secretKey);
        data.put("sign", generateSignature(data));
        Map<String, FileItem> fileItemMap = new HashMap<>();
        FileItem idcardHand = new FileItem();
        idcardHand.setFileName("手持身份证照");
        idcardHand.setFile(convertFileByUrl(bizMerchantEntry.getIdcardhand()));
        FileItem faceRecognizeFace = new FileItem();
        faceRecognizeFace.setFileName("人脸识别照");
        faceRecognizeFace.setFile(convertFileByUrl(bizMerchantEntry.getIdcardhand()));
        FileItem idcardFront = new FileItem();
        idcardFront.setFileName("身份证头像面");
        idcardFront.setFile(convertFileByUrl(bizMerchantEntry.getIdcardfront()));
        FileItem idcardBack = new FileItem();
        idcardBack.setFileName("身份证国徽面");
        idcardBack.setFile(convertFileByUrl(bizMerchantEntry.getIdcardback()));
        FileItem bankcardFront = new FileItem();
        bankcardFront.setFileName("银行卡正面照");
        bankcardFront.setFile(convertFileByUrl(bizMerchantEntry.getBankcardfront()));
        FileItem bankcardBack = new FileItem();
        bankcardBack.setFileName("银行卡背面照");
        bankcardBack.setFile(convertFileByUrl(bizMerchantEntry.getBankcardback()));
        fileItemMap.put("idcardHand", idcardHand);
        fileItemMap.put("faceRecognizeFace", faceRecognizeFace);
        fileItemMap.put("idcardFront", idcardFront);
        fileItemMap.put("idcardBack", idcardBack);
        fileItemMap.put("bankcardFront", bankcardFront);
        fileItemMap.put("bankcardBack", bankcardBack);
        System.out.println("-------------------");
        System.out.println("--------老报件接口-----------");
        System.out.println("-------------------");
        System.out.println("请求参数数据==data------------------------------------》》》" + data);
        System.out.println("请求需要的图片==fileItemMap----------------------------》》》" + fileItemMap);
        String result = HttpClientHandler.onRequest(url, data, fileItemMap);
        System.out.println("返回值返回类型参数==result---------------------------------》》》" + result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String retCode = jsonObject.getString("ret_code");
        String retMsge = jsonObject.getString("ret_msge");
        Object b = jsonObject.getString("data");
        System.out.println("data--------------" + b);
        if (retCode.equals("0")) {
            JSONObject dara1 = jsonObject.getJSONObject("data");
            String merchantNo = dara1.getString("merchant_no");
            bizMerchantEntry.setMerchantNo(merchantNo);// 存入商户编号
            Date date = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            bizMerchantEntry.setCreateTime(format.format(date));
            bizMerchantEntry.setAgentid(secretAgentid);
            // 存储商户信息
            Boolean row = false;
            if (bizMerchantEntry1 == null) {
                row = iBizMerchantEntryService.save(bizMerchantEntry);
                //与报件表关联的  biz_entry_sn
                bizMerchantEntry.setId(bizMerchantEntry.getId());
                   *//*BizEntrySnDTO bizEntrySnDTO=new BizEntrySnDTO();
                bizEntrySnDTO.setCreatTime(format.format(date));
                bizEntrySnDTO.setSn(snCode);
                bizEntrySnDTO.setEntryId(String.valueOf(id));*//*
                //获取mamount_id  费用ID(隐藏)
                //SaInPassFeesDTO saInPassFeesDTO=new SaInPassFeesDTO();
                //saInPassFeesDTO.setSn(bizMerchantEntry.getSn());
                //saInPassFeesDTO.setMerchantNo(merchantNo);
                //SaInPassFeesReturnDTO saInPassFeesReturnDTO=partnerOpenInterfaceController.posSaInPassFeesList(saInPassFeesDTO);
                *//***  在这里写新的 在另一个表里存sn还有报件的id  *****//*
                iBizMerchantEntryService.insertBizEntrySn(bizMerchantEntry);
                *//****             ****//*
                int ok = recordsService.snRecordsOneVersion(bizMerchantEntry);
            } *//*else {
                // 通过merchantNo修改表
                bizMerchantEntry.setId(bizMerchantEntry1.getId());
                iBizMerchantEntryService.saveOrUpdate(bizMerchantEntry);
            }*//*
            if (row) {
                ajaxResult.put("data", true);
                ajaxResult.put("retMsge", retMsge);
            } else {
                ajaxResult.put("data", false);
                ajaxResult.put("retMsge", "报件失败");
            }
            deleteFile(idcardHand.getFile());
            deleteFile(idcardFront.getFile());
            deleteFile(idcardBack.getFile());
            deleteFile(bankcardFront.getFile());
            deleteFile(bankcardBack.getFile());
        } else {
            deleteFile(idcardHand.getFile());
            deleteFile(idcardFront.getFile());
            deleteFile(idcardBack.getFile());
            deleteFile(bankcardFront.getFile());
            deleteFile(bankcardBack.getFile());
            ajaxResult.put("data", false);
            ajaxResult.put("retMsge", retMsge);
            return ajaxResult;
        }
        //查询商户状态
        String urls = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=merchantinfoDao&Methods=load";
        JSONObject dara1 = jsonObject.getJSONObject("data");
        String merchantNo = dara1.getString("merchant_no");
        Map<String, String> dataMap = new HashMap<String, String>();
        dataMap.put("merchant_no", merchantNo);
        dataMap.put("mersource", "OUTMER");
        dataMap.put("agentid", secretAgentid);
        dataMap.put("key", secretKey);
        dataMap.put("sign", PosOneUtil.generateSignature(dataMap));
        String results = HttpClientHandler.noPictureRequest(urls, dataMap);
        System.out.println("查询商户状态返回数据======" + results);
        JSONObject parseObject = JSONObject.parseObject(results);
        String code = parseObject.getString("ret_code");
        if (code.equals("0")) {
            //获取审核状态
            JSONObject data1 = parseObject.getJSONObject("data");
            String proMerSub = data1.getString("pro_mer_sub");
            //更新商户入件状态
            iBizMerchantEntryService.updateMerchantEntry(merchantNo, proMerSub);
            if (proMerSub.equals("3")) {
                //更新激活表状态
                recordsService.updatePosRecordsStatus(snCode);
                //更新设备表
                bizPosMachineService.updatePosPosMachine(snCode);
                //查询流量费收取列表
               // bizFeesChargedService.timerGetChargeList(snCode);
            }
            String proMerSubName = data1.getString("pro_mer_sub_name");
            ajaxResult.put("retMsge", proMerSubName);
        }*/
       // return ajaxResult;
    }

    /**
     * 报件前先在数据库里新增一条数据
     *
     * @return
     */
    @PostMapping("/insertMerchantEntry")
    @Transactional
    public AjaxResult insertMerchantEntry(@RequestBody BizMerchantEntry bizMerchantEntry) {
        AjaxResult ajaxResult = AjaxResult.success("报件，审核");
        System.out.println("新增报件信息");
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        String snCode = bizMerchantEntry.getSn();// 设备号
        //BizMerchantEntry bizMerchantEntry1 = iBizMerchantEntryService.getBizMerchantEntryBySn(snCode);
        BizEntrySnDTO bizMerchantEntry1 = iBizMerchantEntryService.getBizEntrySn(snCode);
        if (bizMerchantEntry1 != null) {
            ajaxResult.put("data", false);
            ajaxResult.put("retMsge", "该设备已存在商户");
            return ajaxResult;
        }
        // 先进行判读
        Long merchId = 0L;
        if (null != bizMerchantEntry.getSn()) {
            String sn = bizMerchantEntry.getSn();
            BizPosMachine bizPosMachine = bizPosMachineService.getPosMachineBySnCode(snCode);
            if (null == bizPosMachine) {
                // 没有该pos机 不允许报件
                ajaxResult.put("data", false);
                ajaxResult.put("retMsge", "该设备不存在");
                return ajaxResult;
            }
            merchId = bizPosMachine.getMerchId();
            bizMerchantEntry.setMerchId(merchId);
        }
        Boolean row = false;
        bizMerchantEntry.setFacerecognizeface("0"); //报件提交了
        if("10285".equals(bizMerchantEntry.getFeeChlId())){
            bizMerchantEntry.setExtraValue("300");
        }else{
            bizMerchantEntry.setExtraValue("0");
        }
        row = iBizMerchantEntryService.save(bizMerchantEntry);

        System.out.println(bizMerchantEntry.getId());
        ajaxResult.put("data",true);
        ajaxResult.put("retMsge","报件成功");
        ajaxResult.put("id", bizMerchantEntry.getId());
        return ajaxResult;
    }

    /**
     * @author: haoran
     * @date: 2022/7/18
     * 方法名称： 规则分辨
     */
    @PostMapping("/rule/Resolution")
    public AjaxResult ruleResolution(@RequestBody BizPlatformIncomingParts bizPlatformIncomingParts) {
        int i = bizMerchantEntryService.insterRuleResolution(bizPlatformIncomingParts);
        if (i > 0) {
            return AjaxResult.success();
        } else {
            return AjaxResult.error();
        }
    }

    /**
     * 新商户报件
     *
     * @return
     */
    @PostMapping("/new/Operation")
    public AjaxResult newStartup(@RequestBody BizMerchantEntry bizMerchantEntry2) throws Exception {
        AjaxResult ajaxResult = AjaxResult.success("新商户报件");
        System.out.println("-----------------------------------");
        System.out.println("----------"+bizMerchantEntry2.getId()+"------------------");
        System.out.println("------------------____--------------------");
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        //先更新一下报件信息
        bizMerchantEntry2.setFacerecognizeface("1");
        bizMerchantEntryService.updateizMerchantEntryFacerecognizeface(bizMerchantEntry2);
        //查询出刚才的报件信息
        BizMerchantEntry bizMerchantEntry = bizMerchantEntryService.selectBizMerchantEntry(bizMerchantEntry2.getId());
       // String snCode = bizMerchantEntryService.selectBizMerchantEntrySn(bizMerchantEntry2.getId());
         //查询商户
        String snCode = bizMerchantEntry.getSn();
        System.out.println("-------------------");
        System.out.println("--------新 报 件 接 口-----------");
        System.out.println("-------------------");
        BizMerchant bizMerchant = bizMerchantService.selectBizMerchantBySN(bizMerchantEntry.getSn());
      //  bizMerchantEntry.setSn(snCode);
        String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=merchantinfoDao&Methods=add";
        Map<String, String> data = new HashMap<String, String>();
        data.put("phone", bizMerchantEntry.getPhone());// 手机号
        data.put("applicant", bizMerchantEntry.getApplicant());// 姓名
        data.put("provinceno", bizMerchantEntry.getProvinceno());// 省编号
        data.put("cityno", bizMerchantEntry.getCityno());// 城市编号
        data.put("areano", bizMerchantEntry.getAreano());// 区编号
        data.put("certificateno", bizMerchantEntry.getCertificateno());// 身份证
        data.put("certificatestartdate", bizMerchantEntry.getCertificatestartdate());// 身份证开始时间
        data.put("certificateenddate", bizMerchantEntry.getCertificateenddate());// 身份证结束时间
        data.put("bankcardaccount", bizMerchantEntry.getBankcardaccount());// 银行卡号

        data.put("merchantname", bizMerchantEntry.getMerchantname());// 费率终端id
        data.put("mcccode", bizMerchantEntry.getMcccode());// 费率终端id
        if("10285".equals(bizMerchantEntry.getFeeChlId())){
            data.put("extra_value","300");// 附加费
            data.put("fee_chl_id", "111");// 费率终端id
        }else{
            data.put("extra_value","0");// 附加费
            data.put("fee_chl_id", bizMerchantEntry.getFeeChlId());// 费率终端id
        }
        data.put("sn", bizMerchantEntry.getSn());// 设备号
        data.put("mersource", "OUTMER");
        data.put("agentid", bizAgentidAppkeyDTO.getAgentid());
        data.put("key", bizAgentidAppkeyDTO.getKey());
        data.put("sign", generateSignature(data));
        Map<String, FileItem> fileItemMap = new HashMap<>();
        FileItem idcardHand = new FileItem();
        idcardHand.setFileName("手持身份证照");
        idcardHand.setFile(convertFileByUrl(bizMerchantEntry.getIdcardhand()));
        FileItem faceRecognizeFace = new FileItem();
        faceRecognizeFace.setFileName("人脸识别照");
        faceRecognizeFace.setFile(convertFileByUrl(bizMerchantEntry.getIdcardhand()));
        FileItem idcardFront = new FileItem();
        idcardFront.setFileName("身份证头像面");
        idcardFront.setFile(convertFileByUrl(bizMerchantEntry.getIdcardfront()));
        FileItem idcardBack = new FileItem();
        idcardBack.setFileName("身份证国徽面");
        idcardBack.setFile(convertFileByUrl(bizMerchantEntry.getIdcardback()));
        FileItem bankcardFront = new FileItem();
        bankcardFront.setFileName("银行卡正面照");
        bankcardFront.setFile(convertFileByUrl(bizMerchantEntry.getBankcardfront()));
        FileItem bankcardBack = new FileItem();
        bankcardBack.setFileName("银行卡背面照");
        bankcardBack.setFile(convertFileByUrl(bizMerchantEntry.getBankcardback()));
        fileItemMap.put("idcardHand", idcardHand);
        fileItemMap.put("faceRecognizeFace", faceRecognizeFace);
        fileItemMap.put("idcardFront", idcardFront);
        fileItemMap.put("idcardBack", idcardBack);
        fileItemMap.put("bankcardFront", bankcardFront);
        fileItemMap.put("bankcardBack", bankcardBack);
        System.out.println("请求参数数据==data------------------------------------》》》" + data);
        System.out.println("请求需要的图片==fileItemMap----------------------------》》》" + fileItemMap);
        String result = HttpClientHandler.onRequest(url, data, fileItemMap);
        System.out.println("返回值返回类型参数==result---------------------------------》》》" + result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String retCode = jsonObject.getString("ret_code");
        String retMsge = jsonObject.getString("ret_msge");
        Object b = jsonObject.getString("data");
        System.out.println("data--------------" + b);
        if (retCode.equals("0")) {
            JSONObject dara1 = jsonObject.getJSONObject("data");
            String merchantNo = dara1.getString("merchant_no");
            bizMerchantEntry.setMerchantNo(merchantNo);// 存入商户编号
            Date date = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            bizMerchantEntry.setCreateTime(format.format(date));
            bizMerchantEntry.setAgentid(bizAgentidAppkeyDTO.getAgentid());

            bizMerchantEntry.setCreateTime(format.format(new Date()));
            /***  在这里写新的 在另一个表里存sn还有报件的id  *****/
            iBizMerchantEntryService.insertBizEntrySn(bizMerchantEntry);
            // 存储商户信息
            int row = 0;
            //去更新这个表
            row = bizMerchantEntryService.upDateBizMerchantEntryMerchantNo(bizMerchantEntry);
            /****             ****/
            int ok = recordsService.snRecordsOneVersion(bizMerchantEntry);
            //插入消息通知
            BizMessageRecords bizMessageRecords = new BizMessageRecords();
            bizMessageRecords.setMsgUserId(bizMerchant.getUserId());
            bizMessageRecords.setMsgContent("SN:"+snCode+",审核成功");
            bizMessageRecords.setMsgStatus(0);
            bizMessageRecords.setMsgType(9);
            bizMessageRecords.setReadStatus(0);
            bizMessageRecords.setAdviceType(1);
            bizMessageRecordsService.save(bizMessageRecords);
             /*else {
                // 通过merchantNo修改表
                bizMerchantEntry.setId(bizMerchantEntry1.getId());
                iBizMerchantEntryService.saveOrUpdate(bizMerchantEntry);
            }*/
            if (row > 0) {
                System.out.println("----同步报件---");
                Long merchId =bizMerchantEntryService.setBizPlatformSync(SecurityUtils.getLoginUser().getUser().getUserId());
                if(merchId!=null){
                    System.out.println("同步报件merchId"+merchId);
                    bizMerchantEntry.setMerchId(merchId);
                    System.out.println(bizMerchantEntry);
                    sendSlm(bizMerchantEntry);
                }
                ajaxResult.put("data", true);
                ajaxResult.put("retMsge", retMsge);
            } else {
                ajaxResult.put("data", false);
                ajaxResult.put("retMsge", "报件失败");
            }
            deleteFile(idcardHand.getFile());
            deleteFile(idcardFront.getFile());
            deleteFile(idcardBack.getFile());
            deleteFile(bankcardFront.getFile());
            deleteFile(bankcardBack.getFile());
        } else {
            deleteFile(idcardHand.getFile());
            deleteFile(idcardFront.getFile());
            deleteFile(idcardBack.getFile());
            deleteFile(bankcardFront.getFile());
            deleteFile(bankcardBack.getFile());
            ajaxResult.put("data", false);
            ajaxResult.put("retMsge", retMsge);
            BizMerchantEntry bizMerchantEntry3 = bizMerchantEntryService.selectBizMerchantEntry(bizMerchantEntry2.getId());
            if( bizMerchantEntry3.getMerchantNo()==null){
                //推送消息
                BizMessageRecords bizMessageRecords = new BizMessageRecords();
                bizMessageRecords.setMsgUserId(bizMerchant.getUserId());
                bizMessageRecords.setMsgContent("SN:"+snCode+",审核失败，原因:"+retMsge);
                bizMessageRecords.setMsgStatus(0);
                bizMessageRecords.setMsgType(9);
                bizMessageRecords.setReadStatus(0);
                bizMessageRecords.setAdviceType(1);
                bizMessageRecordsService.save(bizMessageRecords);
                //把错误信息附上
                bizMerchantEntryService.updateizMerchantEntryErroMessage(bizMerchantEntry2.getId(),retMsge);
                //报件失败了 要 把新增的数据删掉
               // bizMerchantEntryService.deleteMerchantEntry(bizMerchantEntry.getId(),snCode);
            }
            return ajaxResult;
        }
        //查询商户状态
        String urls = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=merchantinfoDao&Methods=load";
        JSONObject dara1 = jsonObject.getJSONObject("data");
        String merchantNo = dara1.getString("merchant_no");
        Map<String, String> dataMap = new HashMap<String, String>();
        dataMap.put("merchant_no", merchantNo);
        dataMap.put("mersource", "OUTMER");
        dataMap.put("agentid", bizAgentidAppkeyDTO.getAgentid());
        dataMap.put("key", bizAgentidAppkeyDTO.getKey());
        dataMap.put("sign", PosOneUtil.generateSignature(dataMap));
        String results = HttpClientHandler.noPictureRequest(urls, dataMap);
        System.out.println("查询商户状态返回数据======" + results);
        JSONObject parseObject = JSONObject.parseObject(results);
        String code = parseObject.getString("ret_code");
        if (code.equals("0")) {
            //获取审核状态
            JSONObject data1 = parseObject.getJSONObject("data");
            String proMerSub = data1.getString("pro_mer_sub");
            //更新商户入件状态
            iBizMerchantEntryService.updateMerchantEntry(merchantNo, proMerSub);
            if (proMerSub.equals("3")) {
                //更新激活表状态
                recordsService.updatePosRecordsStatus(snCode);
                //更新设备表
                bizPosMachineService.updatePosPosMachine(snCode);
                //查询流量费收取列表
                //bizFeesChargedService.timerGetChargeList(snCode);
//                if(bizMerchantEntry.getMerchId()!=null){
//                    sendProMerSub(bizMerchantEntry);
//                }
            }
            String proMerSubName = data1.getString("pro_mer_sub_name");
            ajaxResult.put("retMsge", proMerSubName);
        }
        return ajaxResult;
    }



    /**
     * 新商户报件小程序
     *
     * @return
     */
    @PostMapping("/noToken/new/Operation")
    public AjaxResult noTokenNewStartup(@RequestBody BizMerchantEntry bizMerchantEntry2) throws Exception {
        AjaxResult ajaxResult = AjaxResult.success("新商户报件");
        System.out.println("-----------------------------------");
        System.out.println("----------"+bizMerchantEntry2.getId()+"------------------");
        System.out.println("------------------____--------------------");
        BizAgentidAppkeyDTO bizAgentidAppkeyDTO= bizMerchantReceiverService.getAgentidAppkey(SecurityUtils.getLoginUser().getUser().getUserId());
        //先更新一下报件信息
        bizMerchantEntry2.setFacerecognizeface("1");
        bizMerchantEntryService.updateizMerchantEntryFacerecognizeface(bizMerchantEntry2);
        //查询出刚才的报件信息
        BizMerchantEntry bizMerchantEntry = bizMerchantEntryService.selectBizMerchantEntry(bizMerchantEntry2.getId());
        // String snCode = bizMerchantEntryService.selectBizMerchantEntrySn(bizMerchantEntry2.getId());
        //查询商户
        String snCode = bizMerchantEntry.getSn();
        System.out.println("-------------------");
        System.out.println("--------新 报 件 接 口-----------");
        System.out.println("-------------------");
        BizMerchant bizMerchant = bizMerchantService.selectBizMerchantBySN(bizMerchantEntry.getSn());
        //  bizMerchantEntry.setSn(snCode);
        String url = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=merchantinfoDao&Methods=add";
        Map<String, String> data = new HashMap<String, String>();
        data.put("phone", bizMerchantEntry.getPhone());// 手机号
        data.put("applicant", bizMerchantEntry.getApplicant());// 姓名
        data.put("provinceno", bizMerchantEntry.getProvinceno());// 省编号
        data.put("cityno", bizMerchantEntry.getCityno());// 城市编号
        data.put("areano", bizMerchantEntry.getAreano());// 区编号
        data.put("certificateno", bizMerchantEntry.getCertificateno());// 身份证
        data.put("certificatestartdate", bizMerchantEntry.getCertificatestartdate());// 身份证开始时间
        data.put("certificateenddate", bizMerchantEntry.getCertificateenddate());// 身份证结束时间
        data.put("bankcardaccount", bizMerchantEntry.getBankcardaccount());// 银行卡号
        data.put("merchantname", bizMerchantEntry.getMerchantname());// 费率终端id
        data.put("mcccode", bizMerchantEntry.getMcccode());// 费率终端id
        if("10285".equals(bizMerchantEntry.getFeeChlId())){
            data.put("extra_value","300");// 附加费
            data.put("fee_chl_id", "111");// 费率终端id
        }else{
            data.put("extra_value","0");// 附加费
            data.put("fee_chl_id", bizMerchantEntry.getFeeChlId());// 费率终端id
        }
        data.put("sn", bizMerchantEntry.getSn());// 设备号
        data.put("mersource", "OUTMER");
        data.put("agentid", bizAgentidAppkeyDTO.getAgentid());
        data.put("key", bizAgentidAppkeyDTO.getKey());
        data.put("sign", generateSignature(data));
        Map<String, FileItem> fileItemMap = new HashMap<>();
        FileItem idcardHand = new FileItem();
        idcardHand.setFileName("手持身份证照");
        idcardHand.setFile(convertFileByUrl(bizMerchantEntry.getIdcardhand()));
        FileItem faceRecognizeFace = new FileItem();
        faceRecognizeFace.setFileName("人脸识别照");
        faceRecognizeFace.setFile(convertFileByUrl(bizMerchantEntry.getIdcardhand()));
        FileItem idcardFront = new FileItem();
        idcardFront.setFileName("身份证头像面");
        idcardFront.setFile(convertFileByUrl(bizMerchantEntry.getIdcardfront()));
        FileItem idcardBack = new FileItem();
        idcardBack.setFileName("身份证国徽面");
        idcardBack.setFile(convertFileByUrl(bizMerchantEntry.getIdcardback()));
        FileItem bankcardFront = new FileItem();
        bankcardFront.setFileName("银行卡正面照");
        bankcardFront.setFile(convertFileByUrl(bizMerchantEntry.getBankcardfront()));
        FileItem bankcardBack = new FileItem();
        bankcardBack.setFileName("银行卡背面照");
        bankcardBack.setFile(convertFileByUrl(bizMerchantEntry.getBankcardback()));
        fileItemMap.put("idcardHand", idcardHand);
        fileItemMap.put("faceRecognizeFace", faceRecognizeFace);
        fileItemMap.put("idcardFront", idcardFront);
        fileItemMap.put("idcardBack", idcardBack);
        fileItemMap.put("bankcardFront", bankcardFront);
        fileItemMap.put("bankcardBack", bankcardBack);
        System.out.println("请求参数数据==data------------------------------------》》》" + data);
        System.out.println("请求需要的图片==fileItemMap----------------------------》》》" + fileItemMap);
        String result = HttpClientHandler.onRequest(url, data, fileItemMap);
        System.out.println("返回值返回类型参数==result---------------------------------》》》" + result);
        JSONObject jsonObject = JSONObject.parseObject(result);
        String retCode = jsonObject.getString("ret_code");
        String retMsge = jsonObject.getString("ret_msge");
        Object b = jsonObject.getString("data");
        System.out.println("data--------------" + b);
        if (retCode.equals("0")) {
            JSONObject dara1 = jsonObject.getJSONObject("data");
            String merchantNo = dara1.getString("merchant_no");
            bizMerchantEntry.setMerchantNo(merchantNo);// 存入商户编号
            Date date = new Date();
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            bizMerchantEntry.setCreateTime(format.format(date));
            bizMerchantEntry.setAgentid(bizAgentidAppkeyDTO.getAgentid());

            bizMerchantEntry.setCreateTime(format.format(new Date()));
            /***  在这里写新的 在另一个表里存sn还有报件的id  *****/
            iBizMerchantEntryService.insertBizEntrySn(bizMerchantEntry);
            // 存储商户信息
            int row = 0;
            //去更新这个表
            row = bizMerchantEntryService.upDateBizMerchantEntryMerchantNo(bizMerchantEntry);
            /****             ****/
            int ok = recordsService.snRecordsOneVersion(bizMerchantEntry);
            //插入消息通知
            BizMessageRecords bizMessageRecords = new BizMessageRecords();
            bizMessageRecords.setMsgUserId(bizMerchant.getUserId());
            bizMessageRecords.setMsgContent("SN:"+snCode+",审核成功");
            bizMessageRecords.setMsgStatus(0);
            bizMessageRecords.setMsgType(9);
            bizMessageRecords.setReadStatus(0);
            bizMessageRecords.setAdviceType(1);
            bizMessageRecordsService.save(bizMessageRecords);
             /*else {
                // 通过merchantNo修改表
                bizMerchantEntry.setId(bizMerchantEntry1.getId());
                iBizMerchantEntryService.saveOrUpdate(bizMerchantEntry);
            }*/
            if (row > 0) {
                ajaxResult.put("data", true);
                ajaxResult.put("retMsge", retMsge);
            } else {
                ajaxResult.put("data", false);
                ajaxResult.put("retMsge", "报件失败");
            }
            deleteFile(idcardHand.getFile());
            deleteFile(idcardFront.getFile());
            deleteFile(idcardBack.getFile());
            deleteFile(bankcardFront.getFile());
            deleteFile(bankcardBack.getFile());
        } else {
            deleteFile(idcardHand.getFile());
            deleteFile(idcardFront.getFile());
            deleteFile(idcardBack.getFile());
            deleteFile(bankcardFront.getFile());
            deleteFile(bankcardBack.getFile());
            ajaxResult.put("data", false);
            ajaxResult.put("retMsge", retMsge);
            BizMerchantEntry bizMerchantEntry3 = bizMerchantEntryService.selectBizMerchantEntry(bizMerchantEntry2.getId());
            if("".equals(bizMerchantEntry3.getMerchantNo()) || bizMerchantEntry3.getMerchantNo()==null){
                //推送消息
                BizMessageRecords bizMessageRecords = new BizMessageRecords();
                bizMessageRecords.setMsgUserId(bizMerchant.getUserId());
                bizMessageRecords.setMsgContent("SN:"+snCode+",审核失败，原因:"+retMsge);
                bizMessageRecords.setMsgStatus(0);
                bizMessageRecords.setMsgType(9);
                bizMessageRecords.setReadStatus(0);
                bizMessageRecords.setAdviceType(1);
                bizMessageRecordsService.save(bizMessageRecords);
                //把错误信息附上
                bizMerchantEntryService.updateizMerchantEntryErroMessage(bizMerchantEntry2.getId(),retMsge);
                //报件失败了 要 把新增的数据删掉
                // bizMerchantEntryService.deleteMerchantEntry(bizMerchantEntry.getId(),snCode);
            }
            return ajaxResult;
        }
        //查询商户状态
        String urls = "http://wx.wenwenpay.com.cn:6080/vipf/merchantinfo.do?action=handleAction&beanName=merchantinfoDao&Methods=load";
        JSONObject dara1 = jsonObject.getJSONObject("data");
        String merchantNo = dara1.getString("merchant_no");
        Map<String, String> dataMap = new HashMap<String, String>();
        dataMap.put("merchant_no", merchantNo);
        dataMap.put("mersource", "OUTMER");
        dataMap.put("agentid", bizAgentidAppkeyDTO.getAgentid());
        dataMap.put("key", bizAgentidAppkeyDTO.getKey());
        dataMap.put("sign", PosOneUtil.generateSignature(dataMap));
        String results = HttpClientHandler.noPictureRequest(urls, dataMap);
        System.out.println("查询商户状态返回数据======" + results);
        JSONObject parseObject = JSONObject.parseObject(results);
        String code = parseObject.getString("ret_code");
        if (code.equals("0")) {
            //获取审核状态
            JSONObject data1 = parseObject.getJSONObject("data");
            String proMerSub = data1.getString("pro_mer_sub");
            //更新商户入件状态
            iBizMerchantEntryService.updateMerchantEntry(merchantNo, proMerSub);
            if (proMerSub.equals("3")) {
                //更新激活表状态
                recordsService.updatePosRecordsStatus(snCode);
                //更新设备表
                bizPosMachineService.updatePosPosMachine(snCode);
                //查询流量费收取列表
               // bizFeesChargedService.timerGetChargeList(snCode);
//                sendProMerSub(bizMerchantEntry);
            }
            String proMerSubName = data1.getString("pro_mer_sub_name");
            ajaxResult.put("retMsge", proMerSubName);
        }
        return ajaxResult;
    }

    public static String generateSignature(Map<String, String> data) throws Exception {
        Set<String> keySet = data.keySet();
        String[] keyArray = keySet.toArray(new String[keySet.size()]);
        Arrays.sort(keyArray);
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < keyArray.length; i++) {
            String k = keyArray[i];
            if (data.get(k) != null) { // 参数值为空，则不参与签名
                sb.append(k).append("=").append(data.get(k).trim());
                if (i != keyArray.length - 1) {
                    sb.append("&");
                }
            }
        }
        return md5(sb.toString()).toUpperCase();
    }
/*同步晟联盟新商户报件*/
    private String  sendSlm(BizMerchantEntry bizMerchantEntry) {
        String url="http://www.poshb.cn:8083/pos/synchronization/lmhb/samePosEntry";
        Map<String, String> data = new HashMap<String, String>();
        data.put("phone", bizMerchantEntry.getPhone());// 手机号
        data.put("isAudit", "0");// 审核状态
        data.put("applicant", bizMerchantEntry.getApplicant());// 姓名
        data.put("provinceno", bizMerchantEntry.getProvinceno());// 省编号
        data.put("cityno", bizMerchantEntry.getCityno());// 城市编号
        data.put("areano", bizMerchantEntry.getAreano());// 区编号
        data.put("certificateno", bizMerchantEntry.getCertificateno());// 身份证
        data.put("certificatestartdate", bizMerchantEntry.getCertificatestartdate());// 身份证开始时间
        data.put("certificateenddate", bizMerchantEntry.getCertificateenddate());// 身份证结束时间
        data.put("bankcardaccount", bizMerchantEntry.getBankcardaccount());// 银行卡号
        data.put("feeChlId", bizMerchantEntry.getFeeChlId());// 费率终端id
        data.put("sn", bizMerchantEntry.getSn());// 费率终端id
        data.put("merchId", String.valueOf(bizMerchantEntry.getMerchId()));// 晟联盟的代理
        data.put("idcardhand", bizMerchantEntry.getIdcardhand());// 设备号
        data.put("facerecognizeface", bizMerchantEntry.getFacerecognizeface());// 设备号
        data.put("idcardfront", bizMerchantEntry.getIdcardfront());// 设备号
        data.put("idcardback", bizMerchantEntry.getIdcardback());// 设备号
        data.put("bankcardfront", bizMerchantEntry.getBankcardfront());// 设备号
        data.put("bankcardback", bizMerchantEntry.getBankcardback());// 设备号
        data.put("merchantNo", bizMerchantEntry.getMerchantNo());// 设备号
        data.put("createTime", bizMerchantEntry.getCreateTime());// 设备号
        data.put("agentid", bizMerchantEntry.getAgentid());// 设备号
        String result = doPost(url, new Gson().toJson(data));
        JSONObject jsonObject = JSONObject.parseObject(result);
        String ret_code = jsonObject.getString("ret_code");
        return  ret_code;
    }

    private String  sendProMerSub(BizMerchantEntry bizMerchantEntry) {
        String url="http://www.poshb.cn:8083/pos/synchronization/lmhb/samePosIsAudit";
        Map<String, String> data = new HashMap<String, String>();
        data.put("isAudit",bizMerchantEntry.getIsAudit() );//
        data.put("sn",bizMerchantEntry.getSn() );//
        data.put("merchantNo",bizMerchantEntry.getMerchantNo() );//
        String result = doPost(url, new Gson().toJson(data));
        JSONObject jsonObject = JSONObject.parseObject(result);
        String ret_code = jsonObject.getString("ret_code");
        return  ret_code;
    }

    /*//**
     * 方法描述:将字符串MD5加码 生成32位md5码
     *
     * @author leon 2016年10月10日 下午3:02:30
     * @param inStr
     * @return
     */
    public static String md5(String inStr) {
        try {
            return DigestUtils.md5Hex(inStr.getBytes("UTF-8"));
        } catch (UnsupportedEncodingException e) {
            throw new RuntimeException("MD5签名过程中出现错误");
        }
    }

    public static File convertFileByUrl(String url) {
        //对本地文件命名
        String fileName = url.substring(url.lastIndexOf("."), url.length());
        File file = null;
        URL urlfile;
        InputStream inStream = null;
        OutputStream os = null;
        try {
            file = File.createTempFile("net_url", fileName);
            //下载
            urlfile = new URL(url);
            inStream = urlfile.openStream();
            os = new FileOutputStream(file);

            int bytesRead = 0;
            byte[] buffer = new byte[8192];
            while ((bytesRead = inStream.read(buffer, 0, 8192)) != -1) {
                os.write(buffer, 0, bytesRead);
            }
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (null != os) {
                    os.close();
                }
                if (null != inStream) {
                    inStream.close();
                }

            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return file;
    }

    /*
     * 如果是文件 ==》直接删除
     * 如果是目录 ==》必须先删除里面每一层目录里的所有文件，最后才能删除外层的目录
     *              原因：不为空的话 删不了
     */
    public static void deleteFile(File file) {
        if (file.exists()) {//判断路径是否存在
            if (file.isFile()) {//boolean isFile():测试此抽象路径名表示的文件是否是一个标准文件。
                file.delete();
            } else {//不是文件，对于文件夹的操作
                //保存 路径D:/1/新建文件夹2  下的所有的文件和文件夹到listFiles数组中
                File[] listFiles = file.listFiles();//listFiles方法：返回file路径下所有文件和文件夹的绝对路径
                for (File file2 : listFiles) {
                    /*
                     * 递归作用：由外到内先一层一层删除里面的文件 再从最内层 反过来删除文件夹
                     *    注意：此时的文件夹在上一步的操作之后，里面的文件内容已全部删除
                     *         所以每一层的文件夹都是空的  ==》最后就可以直接删除了
                     */
                    deleteFile(file2);
                }
            }
            file.delete();
        } else {
            System.out.println("该file路径不存在！！");
        }
    }
    /**
     * post请求
     * @param url
     * @param data
     * @return
     */
    public String doPost(String url,String data){
        //创建httpClient对象
        CloseableHttpClient httpClient = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String result = "";
        try{
            //创建http请求
            HttpPost httpPost = new HttpPost(url);
            httpPost.addHeader("Content-Type", "application/json;charset=utf-8");
            //创建请求内容
            String jsonStr = data;
            StringEntity entity = new StringEntity(jsonStr,"utf-8");
            httpPost.setEntity(entity);
            response = httpClient.execute(httpPost);
            result = EntityUtils.toString(response.getEntity(),"utf-8");
            System.out.println(result);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            //关闭资源
            if(response != null){
                try {
                    response.close();
                }catch (IOException ioe){
                    ioe.printStackTrace();
                }
            }
            if(httpClient != null){
                try{
                    httpClient.close();
                }catch (IOException ioe){
                    ioe.printStackTrace();
                }
            }
        }
        return result;
    }
}
